<template>
  <div class="rightBodyContent">
    <div class="rightBodyContent-in" v-if="activeDetail">
      <div>
        <el-button type="primary" plain @click="goBack" size="small"><i class="el-icon-back"></i>返回列表</el-button>
      </div>
      <div class="cornerDetail-info">
        <div class="cornerDetail-info-left">
          <span>区角名称：</span>
          <span>{{ cornerDetail.name }}</span>
        </div>
        <div class="cornerDetail-info-right">
          <span>今日预约：</span>
          <span><i>{{ cornerDetail.use_number }}</i>人</span>
          <span @click="studentVisible=true">查看详细学生信息</span>
        </div>
        <div class="cornerDetail-info-right-line">
          <el-button size="mini" type="primary" round @click="studentComment('commoent')">学生点评</el-button>
          <el-button size="mini" type="primary" round @click="studentComment('collection')">学生采集</el-button>
          <span>设备状态：{{ deviceStatus }}</span>
        </div>
      </div>
      <el-tabs type="card" v-model="activeName">
        <el-tab-pane name="1" label="未预约">
          <span slot="label"><i class="el-icon-folder-checked"></i> 正常（{{
              tabLength[1]
            }}）</span>
          <cornerTableModle tableType="1" :studentOption="activeDetail[1]" v-if="activeName==1"></cornerTableModle>
        </el-tab-pane>
        <el-tab-pane label="离去" name="0">
          <span slot="label"><i class="el-icon-folder-remove"></i> 离去（{{
              tabLength[0]
            }}）</span>
          <cornerTableModle tableType="0" :studentOption="activeDetail[0]" v-if="activeName==0"></cornerTableModle>
        </el-tab-pane>
        <el-tab-pane label="失约" name="3">
          <span slot="label"><i class="el-icon-folder-delete"></i> 失约（{{
              tabLength[3]
            }}）</span>
          <cornerTableModle tableType="3" :studentOption="activeDetail[3]" v-if="activeName==3"></cornerTableModle>
        </el-tab-pane>
        <el-tab-pane label="未预约" name="2">
          <span slot="label"><i class="el-icon-folder"></i> 未预约（{{
              tabLength[2]
            }}）</span>
          <cornerTableModle tableType="2" :studentOption="activeDetail[2]" v-if="activeName==2"></cornerTableModle>
        </el-tab-pane>
      </el-tabs>
      <!--      查看当天预约的学生-->
      <cornerStudentModle :visible.sync="studentVisible" :cornerDetail="cornerDetail"></cornerStudentModle>
      <lookcorner :dishOption="dishOption" :visible.sync="cornerVisible"></lookcorner>
      <cornerComment :visible.sync="cornerCommentVisible" :cornerId="cornerDetail"
                     :cornerCommentType="cornerCommentType"></cornerComment>
    </div>
  </div>
</template>

<script>
import lookcorner from '@/components/dialog/lookcorner.vue'
import cornerComment from './common/cornerComment'

export default {
  components: {
    lookcorner,
    cornerComment
  },
  watch: {
    activeDetail() {
      console.log('数据变更', this.activeDetail)
    }
  },
  data() {
    return {
      activeName: '1',
      studentVisible: false,
      cornerCommentVisible: false, // 点评
      dishOption: null,
      cornerVisible: false,
      cornerDetail: null,
      ws: {},
      tabLength: [0, 0, 0, 0],
      activeDetail: {
        0: {},
        1: {},
        2: {},
        3: {}
      }, // 重组区角数据内容 0离去1在线2未约3失约
      deviceStatus: '',
      cornerCommentType: '',
      clearTime: 0, // 判断是否关闭socket
      clearTimeFn: null
    }
  },
  created() {
    this.cornerDetail = JSON.parse(this.$route.query.detail)
    console.log('this.cornerDetail:', this.cornerDetail)
    this.getSocket(this.cornerDetail.facility_code)
    // console.log('时间内容：', this.formatSeconds(3100))
  },
  methods: {
    goBack() {
      this.$router.go(-1)
    },
    studentComment(option) {
      this.cornerCommentType = option
      this.cornerCommentVisible = true
    },
    // socket对接=======================star
    getSocket(optionId) {
      let n = this;
      // console.log('this.ws', this.ws, this.ws.readyState)
      if (this.ws.readyState === 1) {
        console.log('不需要去连接socket，直接发送区角mac给后台', optionId)
        this.loginsocket(optionId)
      } else {
        console.log('需要去连接socket')
        this.ws = new WebSocket('ws://' + this.$BASE_URL + ':8383')
      }

      this.ws.onmessage = function (res) {
        if (res.data === '1') {
          // console.log('登入成功进行区角推送：', res)
          n.loginsocket(optionId)
        } else {
          console.log('sockt消息推送来了', res)
          clearInterval(n.clearTimeFn) // 清空计时器
          // 5秒计时开始
          // n.clearTime = 0
          // n.getStudentTime() // 开始计时
          n.getCornerArrayFn(res.data)
          // console.log('收到的原始数据：', JSON.parse(res.data))
          // console.log('区角动态返回的数据', res)
        }
      }
      // 成功连上了socket
      this.ws.onopen = () => {
        console.log('成功连上了socket', optionId)
        n.deviceStatus = 'socket连接成功'
      }
      this.ws.onerror = function (err) {
        console.log('失败了ws', err)
        n.deviceStatus = 'socket连接失败'
      }
      this.ws.onclose = function (err) { // 关闭 websocket
        console.log('socket已经关闭了', err)
        n.deviceStatus = 'socket已关闭'
      }
    },
    // 处理socket返回的数据
    getCornerArrayFn(option) {
      // 0离去1在线2未约3失约
      let activeDetail = {
        0: {},
        1: {},
        2: {},
        3: {}
      }
      // console.log('activeDetail:', activeDetail)
      if (option) {
        let a = JSON.parse(option)
        if (a instanceof Array) {
          console.log('收到的数据啊：', a)
          for (let i in a) {
            if (a[i].sum_time) {
              a[i].sum_time = a[i].sum_time ? this.formatSeconds(Number(a[i].sum_time)) : 0;
            }
            // 判断学生类型 activeName当前用户所在的tab
            if (Number(a[i].type) === Number(this.activeName)) {
              this.activeDetail[a[i].type][a[i].id] = this.getJson(a[i])
              this.$set(this.activeDetail, a[i].type, this.getJson(this.activeDetail[a[i].type]))
            }
            activeDetail[a[i].type][a[i].id] = this.getJson(a[i])
            // 此处需要判断是否需要进行正常的验证，比如正常的人离去，数据依旧残留
          }
          // 去除当前状态中不存在的学生,n 学生id
          for (let n in this.activeDetail[this.activeName]) {
            // 当前tab没有数据
            if(!Object.keys(activeDetail[this.activeName]).length){
              this.activeDetail[this.activeName] = {}
            }else{
              if (!activeDetail[this.activeName][n]) {
                delete this.activeDetail[this.activeName][n]
              }
            }
          }
          // 各个状态的人数
          let listLength = [0, 0, 0, 0]
          for (let i in activeDetail) {
            if (Number(i) !== Number(this.activeName)) {
              this.activeDetail[i] = this.getJson(activeDetail[i])
            }
            listLength[i] = Object.keys(activeDetail[i]).length
          }
          this.tabLength = this.getJson(listLength)
          console.log('activeDetail处理实时数据内容：', this.activeDetail)
        }
      }
    },
    // 对socket发送区角信息
    loginsocket(optionId) {
      console.log('发送区角信息到后台')
      this.ws.send(JSON.stringify({
        'mac': optionId,
        'type': 1
      }))
    },
    // 关闭socket
    colseSocket() {
      clearInterval(this.clearTimeFn) // 清空计时器
      this.ws.close()
    },
    // socket===========================end
    // 定时器进行判断区角是否还有人
    getStudentTime() {
      // clearInterval(that.timeNumberFn)
      let n = this;
      this.clearTimeFn = setInterval(() => {
        n.clearTime++
        console.log('计算时间：', n.clearTime)
        if (n.clearTime === 5) {
          n.clearTime = 0
          // 进行清空内容
          this.clearCornerBox()
        }
      }, 1000)
    },
    clearCornerBox() {
      // activeDetail 1 正常 0 离去
      clearInterval(this.clearTimeFn)
      for (let n in this.activeDetail[1]) {
        this.activeDetail[0][this.activeDetail[1][n].id] = this.activeDetail[1][n]
      }
      this.activeDetail[1] = this.getJson({})
      // 各个状态的人数
      let listLength = [0, 0, 0, 0]
      for (let i in this.activeDetail) {
        listLength[i] = Object.keys(this.activeDetail[i]).length
      }
      this.tabLength = this.getJson(listLength)
    },
    getJson(option) {
      return JSON.parse(JSON.stringify(option))
    },
    formatSeconds(value) {
      let result = parseInt(value)
      let h = Math.floor(result / 3600) < 10 ? '0' + Math.floor(result / 3600) : Math.floor(result / 3600);
      let m = Math.floor((result / 60 % 60)) < 10 ? '0' + Math.floor((result / 60 % 60)) : Math.floor((result / 60 % 60));
      let s = Math.floor((result % 60)) < 10 ? '0' + Math.floor((result % 60)) : Math.floor((result % 60));

      let res = '';
      if (h !== '00') res += `${h}时`;
      if (m !== '00') res += `${m}分`;
      res += `${s}秒`;
      return res;
    }
  },
  mounted() {
  },
  // 离开页面关闭socket
  beforeRouteLeave(to, form, next) {
    console.log('页面离开关闭socket！！！进行重置')
    this.colseSocket()
    next()
  }
}
</script>
<style scoped>
.cornerDetail-info {
  display: flex;
  padding: 20px 10px 10px;
  font-size: 14px;
  color: #4c4c4c;
  align-items: center;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

.cornerDetail-info-left {
  margin-right: 30px;
}

.cornerDetail-info-left span:last-child {
  color: #000;
  font-weight: bold;
  font-size: 16px;
}

.cornerDetail-info-right span:nth-child(2) {
  margin-right: 20px;
}

.cornerDetail-info-right span:nth-child(2) i {
  color: #ff8600;
  font-style: normal;
  font-weight: bold;
  font-size: 16px;
}

.cornerDetail-info-right span:nth-child(3) {
  color: #006dcd;
  cursor: pointer;
}

.cornerDetail-info-right-line {
  text-align: right;
  flex: 1;
}


table {
  border-collapse: collapse;
  border: solid 1px #ddd;
}

table th {
  height: 50px;
  background: #dfefff;
}

table td {
  text-align: center;
  padding: 10px;
}

.table-bordered tr td {
  border: 1px solid #ddd;
}

.table-bordered td {
  padding: 8px;
  line-height: 1.42857143;
}
</style>
